package com.itcast.demoone.fragment

import android.content.Context
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import com.itcast.demoone.R


class ListFragment : Fragment() {

    // 定义一个接口用于实现与Activity的通信，当选项被选中时触发
    interface OnItemSelectedListener {
        fun onItemSelected(itemId: Int)
    }

    // 创建接口的引用，用于后续调用方法
    private var listener: OnItemSelectedListener? = null

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_list, container, false)
    }

    /**
     * 视图创建完毕
     */
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        // 1. 给两个按钮设置点击事件监听
        view.findViewById<Button>(R.id.item1).setOnClickListener {
            listener?.onItemSelected(1)
        }
        view.findViewById<Button>(R.id.item2).setOnClickListener {
            listener?.onItemSelected(2)
        }
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        // 确保附加的Context（通常是Activity）实现了所需的接口
        if (context is OnItemSelectedListener) {
            listener = context
        } else {
            throw RuntimeException("$context 必须实现 OnItemSelectedListener")
        }
    }

    override fun onDetach() {
        super.onDetach()
        // 当Fragment分离时，将接口引用设为null以避免内存泄漏
        listener = null
    }
}